// 添加点击跳转页面的事件委派
// 使用广播对象
const bc = new BroadcastChannel("10000"); //10000
const menuContainer = document.querySelector(".menu-container");
const logo = document.querySelector(".sidebar-header");
const search = document.querySelector(".search-box > input");
const searchUl = document.querySelector(".search-ul");

//接受信息 :
bc.addEventListener("message", e => {

    //以前的a标记
    let aActive = menuContainer.querySelector(`a[class="active"]`);

    //当前点击 得到 a标记
    let aTarget = menuContainer.querySelector(`a[href="${e.data}"]`);

    let divActive = menuContainer.querySelector(`div[class="menu-item has-submenu active"]`);


    //现在全局中找到激活状态的 div , 没有找到 那就算了 , 如果找到了 去除active样式

    //点击首页的卡片 取消 class
    if(e.data === "#/main") {
        if(aActive) { //不为空
            aActive.classList.remove("active");
            //删除div的高度
            if(divActive){
                divActive.lastElementChild.style.maxHeight = 0;
                divActive.classList.remove("active");
            }
        }
        return;
    }

    //点击的不是#/main
    let divDoubleParent = aTarget?.parentElement?.parentElement;
    if(divDoubleParent !== divActive){ //点击了自己会收缩
        if(divActive){//不为null的时候
            divActive.lastElementChild.style.maxHeight = 0;
            divActive.classList.remove("active");
        }
    }

    //以前的A标记是谁?
    if(divDoubleParent){
        divDoubleParent.classList.add("active");
        divDoubleParent.lastElementChild.style.maxHeight =`${divDoubleParent.lastElementChild.scrollHeight}px`;
    }

    if(aActive){
        aActive.classList.remove("active"); //把以前的状态清空
    }

    aTarget?.classList?.add("active"); //当前通过e.data找到的A标记



})

menuContainer.addEventListener("click", e => {
    let targetLink = e.target;
    if (targetLink.tagName === 'SPAN') {
        targetLink = targetLink.parentNode;
    }

    // 只有当点击的 a 标签有 href 属性时，才移除其他激活状态
    if (targetLink.tagName === 'A' && targetLink.getAttribute('href')) {
        // 移除所有带有 href 属性的菜单项的激活状态
        const allLinks = document.querySelectorAll('.menu-item a[href], .submenu a[href]');
        allLinks.forEach(link => {
            link.classList.remove('active');
        });

        targetLink.classList.add('active');
        let signal = targetLink.getAttribute('href');

        bc.postMessage(signal); //发送
    }
});

//自动循环生成菜单
menuData.forEach((obj) => {
    //hasOwn == hasOwnProperty : 判断对象是否 存在 指定属性 , 返回bool值
    let div = document.createElement("div");
    div.classList.add("menu-item");
    let a = document.createElement("a");
    let span = document.createElement("span");
    span.textContent = obj.title;

    if (obj.hasOwnProperty("href")) { //有href

        a.setAttribute("href", obj.href);
        a.appendChild(span);
        div.appendChild(a);

    } else {//没有href
        div.classList.add("has-submenu");

        a.classList.add("toggle-submenu");
        a.appendChild(span);
        div.appendChild(a);

        //直接创建div

        //循环生成子标签
        let subDiv = document.createElement("div");
        subDiv.classList.add("submenu");
        obj.submenu.forEach((item) => {
            let subA = document.createElement("a");
            subA.setAttribute("href", item.href);
            let subSpan = document.createElement("span");
            subSpan.textContent = item.title;

            subA.appendChild(subSpan);
            subDiv.appendChild(subA);
            div.appendChild(subDiv);
        });

    }
    menuContainer.appendChild(div);
})

//-------------------------------------------------------------------------------------------------
const toggleSubmenuLinks = document.querySelectorAll('.toggle-submenu');

toggleSubmenuLinks.forEach(link => {
    link.addEventListener('click', function (e) {
        e.preventDefault();
        const parentMenuItem = this.closest('.menu-item');
        const submenu = parentMenuItem.querySelector('.submenu');

        // 关闭其他打开的子菜单
        toggleSubmenuLinks.forEach(otherLink => {
            if (otherLink !== this) {
                const otherParentMenuItem = otherLink.closest('.menu-item');
                const otherSubmenu = otherParentMenuItem.querySelector('.submenu');
                otherSubmenu.style.maxHeight = '0';
                otherParentMenuItem.classList.remove('active');
            }
        });

        // 切换当前子菜单的显示状态
        if (parentMenuItem.classList.contains('active')) {  //submenu不显示  active也没有被添加
            submenu.style.maxHeight = '0';
            parentMenuItem.classList.remove('active');
        } else {
            // 获取子菜单内容的实际高度
            const submenuHeight = submenu.scrollHeight; //不知道有几个a标记
            submenu.style.maxHeight = `${submenuHeight}px`;     //动态高度
            parentMenuItem.classList.add('active');
        }
    });
});

//点击logo添加首页的卡片
logo.addEventListener("click",()=>{
    bc.postMessage("#/main");
})

//搜索
search.onfocus = e =>{
    let sto = null;
    let index = -1;
    let prevTarget = null; //记录li

    //开始输入了
    search.oninput = () =>{
        if(sto){ //节流
            clearTimeout(sto);
        }

        //searchUl是空的
        searchUl.replaceChildren(); //替换 孩子节点数组的

        sto = setTimeout(()=>{
            //搜索关键之
            let promptArray = menuList.filter(title=>{
                if(title.includes(e.target.value)) return title;
            })

            promptArray.forEach(text=>{
                let li = document.createElement("li");
                li.textContent = text;

                li.addEventListener("click",()=>{
                    bc.postMessage(untitles[text]);
                    e.target.value = "";
                    searchUl.style.display = "none";
                })

                //不停地追加ul
                searchUl.appendChild(li);
            })
        },200);

        //显示Ul
        searchUl.style.display = "block";
    }

    document.onkeydown = event=>{
        let childsArray = searchUl.children;

        if(prevTarget){ //不为空
            prevTarget.classList.remove("key-select");
        }

        if(event.key === "Enter"){
            bc.postMessage(untitles[e.target.value]);
            e.target.value = "";
            searchUl.style.display = "none";

        }else if(event.key === "ArrowDown"){
            index++;
            if(index > childsArray.length -1){
                index = childsArray.length -1;
            }
            //伪数组不为空
            if(childsArray.length > 0){
                prevTarget = childsArray[index]; //li
                prevTarget.classList.add("key-select");
                let pivot = computedPivot(searchUl,prevTarget);
                if(index >= pivot ){
                    searchUl.scrollTop += prevTarget.offsetHeight;
                }
                //把li中的title 放到 input中
                e.target.value = prevTarget.textContent;
            }
        }else if(event.key === "ArrowUp"){//index=6
            index--;
            if(index <= 0){
                index = 0;
            }
            if(childsArray.length > 0){
                prevTarget = childsArray[index];
                prevTarget.classList.add("key-select");
                let pivot = computedPivot(searchUl,prevTarget);
                if(index < childsArray.length - pivot){ //7 - 5 = 2
                    searchUl.scrollTop -= prevTarget.offsetHeight;
                }
                //把li中的title 放到 input中
                e.target.value = prevTarget.textContent;
            }

        }else if(event.key === "Backspace"){
            index = -1;
        }
    }
    search.onblur = ()=>{
        setTimeout(function(){
            searchUl.style.display="none";
        },200);

        search.oninput = null;
        document.onkeydown = null;
    }

}

function computedPivot(searchUl,prevTarget){
    let top = parseInt(window.getComputedStyle(searchUl)["border-top-width"].split("px")[0]);
    let btm = parseInt(window.getComputedStyle(searchUl)["border-bottom-width"].split("px")[0]);
    let ulShowMaxHeight = searchUl.clientHeight + btm + top; //200

    let liBtm = parseInt(window.getComputedStyle(prevTarget)["border-bottom-width"].split("px")[0]);
    let liShowMaxHeight = prevTarget.clientHeight + liBtm;

    let pivot = Math.trunc(ulShowMaxHeight / liShowMaxHeight);
    return pivot;
}



